package com.cg.global;

import com.cg.annotation.Encrypt;
import com.cg.config.EncryptProperties;
import com.cg.entity.RespBean;
import com.cg.utils.AESCipher;
import com.cg.utils.AESUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
@RequiredArgsConstructor
public class EncryptResponse implements ResponseBodyAdvice<RespBean> {

    private final EncryptProperties encryptProperties;

    /**
     * 响应体条件筛选判断，true则进行进一步的处理，false不进行处理
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return methodParameter.hasMethodAnnotation(Encrypt.class);
    }

    /**
     * 响应体返回前对相关内容进行处理
     */
    @Override
    public RespBean beforeBodyWrite(RespBean respBean, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        String key = encryptProperties.getKey();
        try {
            if (respBean.getMsg() != null) {
                respBean.setMsg(AESUtils.encrypt(respBean.getMsg(), key));
            }
            if (respBean.getObj() != null) {
                respBean.setObj(AESUtils.encrypt(respBean.getMsg(), key));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return respBean;
    }


}
